package cn.zb.zbrhback.auth.service.impl;

import cn.zb.zbrhback.auth.service.ILoginService;
import cn.zb.zbrhback.basic.util.LoginMap;
import cn.zb.zbrhback.org.domain.Employee;
import cn.zb.zbrhback.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Resource
    private EmployeeMapper employeeMapper;
    @Override
    public Map<String, Object> login(Employee employee) {
        // 参数非空
        if(StringUtils.isEmpty(employee.getUsername()) || StringUtils.isEmpty(employee.getPassword())){
            throw new RuntimeException("用户名或密码不能为空");
        }

        //用户名查询用户
        Employee emp = employeeMapper.loadByName(employee.getUsername());
        if(Objects.isNull(emp)){
            throw new RuntimeException("用户不存在");
        }

        //比对密码
        if(!emp.getPassword().equals(employee.getPassword())){
            throw new RuntimeException("用户名或密码错误");
        }

        Map<String,Object> map = new HashMap<>();
        emp.setPassword("");
        map.put("loginUser",emp);
        String token = UUID.randomUUID().toString();
        map.put("token",token);
        LoginMap.map.put(token,emp);
        return map;
    }
}
